package com.zhuhao.utils.httpclient;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * jdk原生http请求
 * @Author haozhu7
 * @Date 2025/5/20 14:43
 **/
public class JdkHttpClient {

    public static String URL = "http://www.baidu.com";

    @Test
    public void test01() throws IOException {
       try {
           URL url = new URL(URL);
           HttpURLConnection connection = (HttpURLConnection)url.openConnection();
           connection.setRequestMethod("GET");

           int responseCode = connection.getResponseCode();
           if (responseCode == HttpURLConnection.HTTP_OK) {
               System.out.println("请求成功");
           } else {
               System.out.println("请求失败");
               return;
           }

           try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
               String line;
               StringBuilder response = new StringBuilder();
               while ((line = in.readLine()) != null) {
                   response.append(line);
               }
               System.out.println(response);
           }catch (IOException e) {
               e.printStackTrace();
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
